﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace Macaw.Wss4.GoogleAnalyticsSolution.Layouts.Macaw.Wss4.GoogleAnalyticsSolution
{
    public partial class ManageGoogleAnalyticsSettings : LayoutsPageBase
    {

        protected string GetGlobalResourceString(string key)
        {
            return HttpContext.GetGlobalResourceObject("Macaw.Wss4.GoogleAnalyticsSolution.ManageGoogleAnalyticsSettings", key) as string;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && SPContext.Current != null && SPContext.Current.Site != null)
            {
                // Fill the zone dropdownbox
                foreach (string zonename in Enum.GetNames(typeof(Microsoft.SharePoint.Administration.SPUrlZone)))
                {
                    ddlZoneSelector.Items.Add(zonename);
                }

                // Select the current zone in the dropdownbox
                SPUrlZone currentzone = SPContext.Current.Site.Zone;
                string currentzonename = Enum.GetName(typeof(Microsoft.SharePoint.Administration.SPUrlZone), currentzone);
                ListItem currentzoneitem = ddlZoneSelector.Items.FindByText(currentzonename);
                if (currentzoneitem != null)
                {
                    currentzoneitem.Selected = true;
                }

                ShowData();
            }
        }

        protected void ShowData()
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;
            SPUrlZone currentzone = (SPUrlZone)Enum.Parse(typeof(SPUrlZone), ddlZoneSelector.SelectedValue);

            // Display the alternate urls of the currently selected zone
            lblZoneUrls.Text = "";
            foreach (SPAlternateUrl alturl in SPContext.Current.Site.WebApplication.AlternateUrls)
            {
                if (alturl.UrlZone.Equals(currentzone))
                {
                    if (lblZoneUrls.Text.Length > 0) lblZoneUrls.Text += ", ";
                    lblZoneUrls.Text += alturl.IncomingUrl;
                }
            }

            #region TrackerCode
            tbWebTrackerCode.Text = string.Empty;
            rbInherit.Checked = true;
            rbDisable.Checked = false;
            rbOverride.Checked = false;

            string ParentCode = null;
            string TrackerCode = null;
            bool? TAParentValue;
            bool? TEParentValue;
            bool? TAValue;
            bool? TEValue;
            if (Request.QueryString["listurl"] != null)
            {
                string listurl = Request.QueryString["listurl"];
                SPFile file = SPContext.Current.Web.GetFile(listurl);
                SPFolder folder = file.ParentFolder;
                ManageObjectLiteral.Text = folder.ServerRelativeUrl;
                ManageObjectLiteral2.Text = folder.ServerRelativeUrl;
                ParentCode = GoogleAnalyticsHelper.GetTrackerCode(site, folder.ParentFolder, currentzone, true);
                TrackerCode = GoogleAnalyticsHelper.GetTrackerCode(site, folder, currentzone, false);
                TAParentValue = GoogleAnalyticsHelper.GetTrackAuthenticated(site, folder.ParentFolder, currentzone, true);
                TEParentValue = GoogleAnalyticsHelper.GetTrackEditMode(site, folder.ParentFolder, currentzone, true);
                TAValue = GoogleAnalyticsHelper.GetTrackAuthenticated(site, folder, currentzone, false);
                TEValue = GoogleAnalyticsHelper.GetTrackEditMode(site, folder, currentzone, false);
            } else if (Request.QueryString["pageurl"] != null)
            {
                string pageurl = Request.QueryString["pageurl"];
                SPFile file = SPContext.Current.Web.GetFile(pageurl);
                ManageObjectLiteral.Text = file.ServerRelativeUrl;
                ManageObjectLiteral2.Text = file.ServerRelativeUrl;
                ParentCode = GoogleAnalyticsHelper.GetTrackerCode(site, file.ParentFolder, currentzone, true);
                TrackerCode = GoogleAnalyticsHelper.GetTrackerCode(site, file, currentzone, false);
                TAParentValue = GoogleAnalyticsHelper.GetTrackAuthenticated(site, file.ParentFolder, currentzone, true);
                TEParentValue = GoogleAnalyticsHelper.GetTrackEditMode(site, file.ParentFolder, currentzone, true);
                TAValue = GoogleAnalyticsHelper.GetTrackAuthenticated(site, file, currentzone, false);
                TEValue = GoogleAnalyticsHelper.GetTrackEditMode(site, file, currentzone, false);
            }
            else
            {
                ManageObjectLiteral.Text = web.ServerRelativeUrl;
                ManageObjectLiteral2.Text = web.ServerRelativeUrl;
                ParentCode = GoogleAnalyticsHelper.GetTrackerCode(site, web.ParentWeb, currentzone, true);
                TrackerCode = GoogleAnalyticsHelper.GetTrackerCode(site, web, currentzone, false);
                TAParentValue = GoogleAnalyticsHelper.GetTrackAuthenticated(site, web.ParentWeb, currentzone, true);
                TEParentValue = GoogleAnalyticsHelper.GetTrackEditMode(site, web.ParentWeb, currentzone, true);
                TAValue = GoogleAnalyticsHelper.GetTrackAuthenticated(site, web, currentzone, false);
                TEValue = GoogleAnalyticsHelper.GetTrackEditMode(site, web, currentzone, false);
            }

            if (ParentCode == null)
            {
                lblParentCode.Text = GetGlobalResourceString("StatusUndefined");
            }
            else if (ParentCode == string.Empty)
            {
                lblParentCode.Text = GetGlobalResourceString("StatusTrackerCodeDisabled");
            }
            else
            {
                lblParentCode.Text = ParentCode;
            }

            tbWebTrackerCode.Text = string.Empty;
            if (TrackerCode == string.Empty)
            {
                rbDisable.Checked = true;
            }
            else if (TrackerCode == null)
            {
                // rbInherit.Checked = true;
            }
            else
            {
                rbOverride.Checked = true;
                tbWebTrackerCode.Text = TrackerCode;
            }
            #endregion

            #region TrackAuthenticated
            rbTAInherit.Checked = true;
            rbTADisabled.Checked = false;
            rbTAEnabled.Checked = false;

            
            if (!TAParentValue.HasValue)
            {
                lblParentTA.Text = GetGlobalResourceString("StatusUndefined");
            }
            else
            {
                if (TAParentValue.Value)
                {
                    lblParentTA.Text = string.Format(GetGlobalResourceString("Status"), rbTAEnabled.LabelText);
                }
                else
                {
                    lblParentTA.Text = string.Format(GetGlobalResourceString("Status"), rbTADisabled.LabelText);
                }
            }


            if (TAValue.HasValue)
            {
                if (TAValue.Value)
                {
                    rbTAEnabled.Checked = true;
                }
                else
                {
                    rbTADisabled.Checked = true;
                }
            }
            #endregion

            #region TrackEditMode
            rbTEInherit.Checked = true;
            rbTEDisabled.Checked = false;
            rbTEEnabled.Checked = false;

            if (!TEParentValue.HasValue)
            {
                lblParentTE.Text = GetGlobalResourceString("StatusUndefined");
            }
            else
            {
                if (TEParentValue.Value)
                {
                    lblParentTE.Text = string.Format(GetGlobalResourceString("Status"), rbTEEnabled.LabelText);
                }
                else
                {
                    lblParentTE.Text = string.Format(GetGlobalResourceString("Status"), rbTEDisabled.LabelText);
                }
            }

            

            if (TEValue.HasValue)
            {
                if (TEValue.Value)
                {
                    rbTEEnabled.Checked = true;
                }
                else
                {
                    rbTEDisabled.Checked = true;
                }
            }
            #endregion
        }

        public void ZoneChanged(object sender, EventArgs e)
        {
            ShowData();
        }


        public void SaveClick(object sender, EventArgs e)
        {
            if (SPContext.Current != null && SPContext.Current.Web != null)
            {
                try
                {
                    SPUrlZone zone = (SPUrlZone)Enum.Parse(typeof(SPUrlZone), ddlZoneSelector.SelectedValue);
                    if (Request.QueryString["listurl"] != null)
                    {
                        SPFile file = SPContext.Current.Web.GetFile(Request.QueryString["listurl"]);
                        SPFolder folder = file.ParentFolder;
                        if (rbOverride.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(folder, zone, tbWebTrackerCode.Text);
                        }
                        else if (rbDisable.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(folder, zone, string.Empty);
                        }
                        else if (rbInherit.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(folder, zone, null);
                        }

                        if (rbTADisabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(folder, zone, false);
                        }
                        else if (rbTAEnabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(folder, zone, true);
                        }
                        else
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(folder, zone, null);
                        }

                        if (rbTEDisabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(folder, zone, false);
                        }
                        else if (rbTEEnabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(folder, zone, true);
                        }
                        else
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(folder, zone, null);
                        }
                        folder.Update();
                        SPDiagnosticsService ds = SPDiagnosticsService.Local;
                        ds.WriteTrace(0,
                            new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning),
                            TraceSeverity.Verbose, "Settings saved on \"{0}\"",
                            new object[] { folder.ServerRelativeUrl });
                    }
                    else if (Request.QueryString["pageurl"] != null)
                    {
                        SPFile file = SPContext.Current.Web.GetFile(Request.QueryString["pageurl"]);
                        if (rbOverride.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(file, zone, tbWebTrackerCode.Text);
                        }
                        else if (rbDisable.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(file, zone, string.Empty);
                        }
                        else if (rbInherit.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(file, zone, null);
                        }

                        if (rbTADisabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(file, zone, false);
                        }
                        else if (rbTAEnabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(file, zone, true);
                        }
                        else
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(file, zone, null);
                        }

                        if (rbTEDisabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(file, zone, false);
                        }
                        else if (rbTEEnabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(file, zone, true);
                        }
                        else
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(file, zone, null);
                        }

                        file.Update();

                        SPDiagnosticsService ds = SPDiagnosticsService.Local;
                        ds.WriteTrace(0,
                            new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning),
                            TraceSeverity.Verbose, "Settings saved on \"{0}\"",
                            new object[] { file.ServerRelativeUrl });
                    }
                    else
                    {
                        SPFolder folder = SPContext.Current.Web.RootFolder;
                        if (rbOverride.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(folder, zone, tbWebTrackerCode.Text);
                        }
                        else if (rbDisable.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(folder, zone, string.Empty);
                        }
                        else if (rbInherit.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackerCode(folder, zone, null);
                        }

                        if (rbTADisabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(folder, zone, false);
                        }
                        else if (rbTAEnabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(folder, zone, true);
                        }
                        else
                        {
                            GoogleAnalyticsHelper.SetTrackAuthenticated(folder, zone, null);
                        }

                        if (rbTEDisabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(folder, zone, false);
                        }
                        else if (rbTEEnabled.Checked)
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(folder, zone, true);
                        }
                        else
                        {
                            GoogleAnalyticsHelper.SetTrackEditMode(folder, zone, null);
                        }

                        folder.Update();

                        SPDiagnosticsService ds = SPDiagnosticsService.Local;
                        ds.WriteTrace(0,
                            new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning),
                            TraceSeverity.Verbose, "Settings saved on \"{0}\"",
                            new object[] { folder.ServerRelativeUrl });
                    }
                    StatusLabel.Text = GetGlobalResourceString("SavedConfirmation");
                }
                catch (Exception ex)
                {
                    StatusLabel.Text = "Error occured!";

                    SPDiagnosticsService ds = SPDiagnosticsService.Local;
                    ds.WriteTrace(0,
                        new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning),
                        TraceSeverity.Monitorable, "Error saving settings\r\n{2}",
                        new object[] { ex.ToString() });
                }
                ShowData();
            }

        }

    }
}
